package team.future.joke.controller;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

import com.alibaba.fastjson.JSONObject;

import team.future.joke.constant.CollectorConstants;
import team.future.joke.constant.WeixinConstants;
import team.future.joke.util.WebClientUtil;

/**
 * Title: WeixinUtil.java<br>
 * Description: <br>
 * Copyright (c) 未来工作室版权所有 2015    <br>
 * Create DateTime: 2015年9月19日 上午10:45:36 <br>
 * @author futurezhu
*/
public class WeixinUtil {

	/**
	 * 获取签名算法
	 * 首先拼接
	 * jsapi_ticket=token&noncestr=nonce_str&timestamp=timestamp&url=url;
	 * 然后用SHA-1
	 * 最后按照%02x排序
	 * @param token
	 * @return
	 */
	public static String getSignature(String token, String timestamp) {
		String nonce_str = WeixinConstants.NONCESTR;
		String str;
		String signature = "";

		//注意这里参数名必须全部小写，且必须有序
		str = "jsapi_ticket=" + token + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url="
				+ CollectorConstants.REAL_DOMAIN;

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(str.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return signature;
	}

	/**
	 * 转化hash
	 * @param hash
	 * @return
	 */
	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	/**
	 * 获取js token
	 * @return
	 */
	public static String getToken() {
		String param = "&appid=" + WeixinConstants.APPID + "&secret=" + WeixinConstants.APPSECRET;
		String tokenstr = WebClientUtil.sendGet(WeixinConstants.TOKEN_URL + param);
		JSONObject tokenJson = JSONObject.parseObject(tokenstr);
		return tokenJson.getString("access_token");
	}

	/**
	 * 获取当前时间戳
	 * @return
	 */
	public static String getTimeStamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}
